package servlets;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.json.JSONException;
import org.json.JSONObject;

import beans.XsdBean;

@WebServlet(name = "FileUploadServlet", urlPatterns = { "/upload" })
@MultipartConfig
public class FileUploaderServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.print("Get request");
		response.setContentType("application/json");

		// Create path components to save the file
		try {
			final Part filePart = request.getPart("file");

			FileWriter out = null;
			InputStream filecontent = null;
			final PrintWriter writer = response.getWriter();
			String xsdContent = "";
			JSONObject jsonObj = new JSONObject();
			try {
				out = new FileWriter("temp.xsd");
				filecontent = filePart.getInputStream();

				if (filecontent != null) {
					Writer strWriter = new StringWriter();

					char[] buffer = new char[1024];
					Reader reader = new BufferedReader(new InputStreamReader(
							filecontent, "UTF-8"));
					int n;
					while ((n = reader.read(buffer)) != -1) {
						strWriter.write(buffer, 0, n);
					}
					xsdContent = strWriter.toString();
					strWriter.close();
				}
				XsdBean xsd = new XsdBean(xsdContent);
				jsonObj.put("xsdContent", xsdContent);
			} catch (FileNotFoundException fne) {
				try {
					jsonObj.put("error", fne.getMessage());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				writer.println(jsonObj);
				if (out != null) {
					out.flush();
					out.close();
				}
				if (filecontent != null) {
					filecontent.close();
				}
				if (writer != null) {
					writer.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}